import { NextRequest, NextResponse } from 'next/server';
import sqlite3 from 'sqlite3';
import path from 'path';
import { getDatabasePath } from '@/lib/database-path';

const dbPath = getDatabasePath();

interface ContactInfo {
  id: string;
  type: 'wechat_group' | 'wechat_official' | 'qq_group' | 'email' | 'phone' | 'address';
  title: string;
  description?: string;
  content: string;
  qrCode?: string;
  isVisible: boolean;
  order: number;
}

// 初始化数据库表
const initializeDatabase = () => {
  return new Promise<sqlite3.Database>((resolve, reject) => {
    const db = new sqlite3.Database(dbPath, (err) => {
      if (err) {
        reject(err);
        return;
      }
      
      // 创建联系方式表
      db.run(`CREATE TABLE IF NOT EXISTS contacts (
        id TEXT PRIMARY KEY,
        type TEXT NOT NULL,
        title TEXT NOT NULL,
        description TEXT,
        content TEXT NOT NULL,
        qr_code TEXT,
        is_visible INTEGER DEFAULT 1,
        order_num INTEGER DEFAULT 1,
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
        updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
      )`, (err) => {
        if (err) {
          reject(err);
          return;
        }

        // 前台API不再插入任何默认数据，只负责读取
        resolve(db);
      });
    });
  });
};

export async function GET(request: NextRequest) {
  try {
    console.log('前台API: 数据库路径 =', dbPath);
    const db = await initializeDatabase();
    
    return new Promise<NextResponse>((resolve, reject) => {
      // 先查询所有数据看看数据库中到底有什么
      db.all(`SELECT id, type, title, description, content, qr_code, is_visible, order_num FROM contacts ORDER BY order_num ASC`, (err, allRows: any[]) => {
        if (err) {
          console.error('前台API: 查询所有数据失败:', err);
          db.close();
          reject(err);
          return;
        } else {
          console.log('前台API: 数据库中所有联系方式数据:', allRows);
        }
        
        // 然后查询可见的数据
        db.all(`
          SELECT id, type, title, description, content, qr_code as qrCode, is_visible as isVisible, order_num as orderNum
          FROM contacts 
          WHERE is_visible = 1 
          ORDER BY order_num ASC
        `, (err, rows: any[]) => {
          db.close();
          
          if (err) {
            reject(err);
            return;
          }
          
          const contacts: ContactInfo[] = rows.map(row => ({
            id: row.id,
            type: row.type,
            title: row.title,
            description: row.description,
            content: row.content,
            qrCode: row.qrCode,
            isVisible: Boolean(row.isVisible),
            order: row.orderNum
          }));
          
          const response = NextResponse.json({
            success: true,
            data: contacts
          });
          
          // 禁用缓存，确保实时数据
          response.headers.set('Cache-Control', 'no-store, no-cache, must-revalidate, proxy-revalidate');
          response.headers.set('Pragma', 'no-cache');
          response.headers.set('Expires', '0');
          response.headers.set('Surrogate-Control', 'no-store');
          
          resolve(response);
        });
      });
    });
  } catch (error) {
    console.error('获取联系方式失败:', error);
    return NextResponse.json(
      { success: false, error: '获取联系方式失败' },
      { status: 500 }
    );
  }
}